﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using LowLevelGraphics.Filter;

namespace LowLevelGraphics
{
    public interface IConvergable
    {
        //Criteria formula
        int IterationsNeeded { get; set; }
    }

    /// <summary>
    /// Use this to test converging criteria
    /// for example a threshold filter (color -> monochrome) might need only one iteration.
    /// Assign criteria if you'd like to speed up the process
    /// </summary>
    public class ConvergableFilter : MacroFilter, IConvergable
    {
        private int m_nIterations = 1;

        public ConvergableFilter()
        {
            this.m_aFilter.Add(new Threshold2(127));
        }

        public int Iterations
        {
            get { return m_nIterations; }
            set { m_nIterations = value; }
        }

        /// <summary>
        /// Repeat execution until bitmap will not be changed again by filter, i.e. all pixels stay the same AT CONVERGE reached.
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmapOriginal = (UnsafeBitmap)_bitmap.Clone();
            UnsafeBitmap bitmapFiltered = null;
            for (int i = 0; i < m_nIterations; i++)
            {
                bitmapFiltered = base.Execute(_bitmap);
                if (BitmapFunctions.CompareByPixelUnsafe(bitmapOriginal, bitmapFiltered))
                {
                    break;
                }                
            }
            return bitmapFiltered;
        }

        public int IterationsNeeded
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
}
